/************************************
 * Package: RGcpp					*
 * Authors: Rui Eduardo Gouveia Gil	*
 * Date: 2010						*
 ************************************/
#ifndef __RGCPP_DATAGRAMSOCKET_H__
#define __RGCPP_DATAGRAMSOCKET_H__

#include <string>
#include <errno.h>
#include <string.h>

#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#include <winsock2.h>
#else
#include <netdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#endif

#include <boost/thread/mutex.hpp>

#include "rgcpp/net/IPAddress.h"
#include "rgcpp/exceptions/IOException.h"

#define NO_TIMEOUT 0

namespace rgcpp
{

class DatagramSocket
{
	protected:
		int socketFD;
		bool releaseForced;
		IPAddress ipAddress;
		boost::mutex mutRead;
		boost::mutex mutWrite;
		IPAddress peerAddress;
		struct timeval timeout;

	public:
		DatagramSocket();
		DatagramSocket(const unsigned short port);
		DatagramSocket(const IPAddress& ipAddress);
		~DatagramSocket();

		void sendMsg(const char* buffer, const unsigned int size);
		void sendMsg(const char* buffer, const unsigned int size, const IPAddress& ipAddress);

		int receiveMsg(char* buffer, const unsigned int size);
		int receiveMsg(char* buffer, const unsigned int size, IPAddress& ipAddress);

		void setTimeout(unsigned long timeout);
		unsigned long getTimeout();

		void release();

		bool check4readMsg(unsigned long timeout=0);

		IPAddress getLocalAddress();
		IPAddress getPeerAddress();
};

}

#endif
